import com.sun.tools.attach.*;

import java.io.IOException;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by micocube
 * ProjectName: coding
 * PackageName: com.coding.instrumentation
 * User: micocube
 * Email: ldscube@gmail.com
 * CreateTime: 2019/1/17下午3:15
 * ModifyTime: 2019/1/17下午3:15
 * Version: 0.1
 * Description:
 **/
public class LoadAgent {

    public static void main(String[] args) throws Exception {

        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                try {
                    LoadAgent.load("Main",
                            "/Users/micocube/Documents/AgentMain/src/AgentMain.jar",
                            "cxs");

                } catch (IOException e) {
                    e.printStackTrace();
                } catch (AgentLoadException e) {
                    e.printStackTrace();
                } catch (AgentInitializationException e) {
                    e.printStackTrace();
                } catch (AttachNotSupportedException e) {
                    e.printStackTrace();
                }
            }
        },0,3000L);


    }

    public static void load(String appName, String agentJarPath, String agentArgs) throws IOException, AgentLoadException, AgentInitializationException, AttachNotSupportedException {
        System.out.println("agentJarPath"+agentJarPath+",args:"+agentArgs);
        List<VirtualMachineDescriptor> list = VirtualMachine.list();
        for (VirtualMachineDescriptor vmd : list) {
            System.out.println("VirtualMachineDescriptorName:" + vmd.displayName());
            if (vmd.displayName().endsWith(appName)) {
                VirtualMachine virtualMachine = VirtualMachine.attach(vmd.id());
                virtualMachine.loadAgent(agentJarPath, agentArgs);
                virtualMachine.detach();
            }
        }
    }
}
